package com.basic.util;

import cn.hutool.core.collection.CollUtil;
import com.basic.exception.ConvertException;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * author: cjy
 */
public class ConverterUtil {

    public static <R, T> T convert(R source, Class<T> targetClass){
        T target = null;
        try {
            target = targetClass.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            throw new ConvertException("dto数据转换异常");
        }

        BeanUtils.copyProperties(source, target);
        return target;
    }

    public static <R, T> List<T> convert(List<R> sources, Class<T> targetClass){
        if (CollUtil.isEmpty(sources)) {
            return Collections.emptyList();
        }

        final List<T> targets = new ArrayList<>();
        for (R each: sources) {
            targets.add(convert(each, targetClass));
        }

        return targets;
    }

}